package cn.ycc1.boot3redis.controller;

import cn.ycc1.boot3redis.entity.Message;
import cn.ycc1.boot3redis.service.MessageConsumerService;
import cn.ycc1.boot3redis.service.MessageProducerService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ycc
 * @date 2025/11/20
 */
@RestController
@RequestMapping("/api/message")
public class MessageController {

    private final MessageProducerService producerService;
    private final MessageConsumerService consumerService;

    public MessageController(MessageProducerService producerService,
                             MessageConsumerService consumerService) {
        this.producerService = producerService;
        this.consumerService = consumerService;
    }

    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(@RequestBody Message message) {
        try {
            producerService.sendMessage(message);
            return ResponseEntity.ok("消息发送成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("消息发送失败: " + e.getMessage());
        }
    }

    @PostMapping("/send-batch")
    public ResponseEntity<String> sendBatchMessages(@RequestBody List<Message> messages) {
        try {
            producerService.sendMessages(messages);
            return ResponseEntity.ok("批量消息发送成功，共" + messages.size() + "条");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("批量消息发送失败: " + e.getMessage());
        }
    }

    @GetMapping("/queue-size")
    public ResponseEntity<Long> getQueueSize() {
        Long size = producerService.getQueueSize();
        return ResponseEntity.ok(size);
    }

    @PostMapping("/start-consumer")
    public ResponseEntity<String> startConsumer() {
        consumerService.startConsumer();
        return ResponseEntity.ok("消费者已启动");
    }
}
